package cn.kgc.springcloud.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author 课工场
 * @date 2025/1/15
 * @description
 */
@Configuration
public class CustomerBeanConfig {

    @Bean
    public BlockExceptionHandler blockExceptionHandler(){
        return  new BlockExceptionHandler() {
            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
                if (e instanceof FlowException){
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("code",500);
                    result.put("message","当前请求被流控");
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();

                    String jsonStr = JSONUtil.toJsonStr(result);
                    writer.write(jsonStr);
                    writer.close();
                }
            }
        };
    }
}
